package timbap.artwork.gui;

import timbap.artwork.retrieval.ArtworkRetrievalManager;
import timbap.artwork.retrieval.ArtworkRetriever;
import timbap.artwork.retrieval.QueryCreator;
import timbap.artwork.storage.ArtworkFileUpdater;
import timbap.visualizer.api.model.PlaylistEntry;
import timbap.visualizer.impl.context.textures.AbstractP5TextureCacheManager;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PlaylistEntryControlPanel {

    PlaylistEntry playlistEntry;

    JPanel panel;
    JLabel actualImageViewer;
    JToggleButton phraseToggleButton;
    JTextField queryField;
    JButton submitButton;
    Image defaultArtworkImage;
    JLabel resultInfoLabel;

    List<JToggleButton> queryTermButtons = new ArrayList<JToggleButton>();
    List<JButton> imageResultButtons = new ArrayList<JButton>();

    ArtworkRetrievalManager artworkRetrievalManager;

    public Component getComponent() {
        return panel;
    }

    public PlaylistEntryControlPanel(final PlaylistEntry pPlaylistEntry,
                                     final Image pDefaultArtworkImage,
                                     final ArtworkRetriever pArtworkRetriever) {

        defaultArtworkImage = pDefaultArtworkImage;
        playlistEntry = pPlaylistEntry;
        List<String> tQueryTerms = findQueryTerms();

        actualImageViewer = createActualImageViewer();
        JPanel tQueryTermButtonsPanel = createQueryTermButtonsPanel(tQueryTerms);
        JPanel tSearchControlPanel = createSearchControlPanel();
        ActionListener tQueryChangeListener = createQueryChangeListener();
        phraseToggleButton.addActionListener(tQueryChangeListener);
        for (JToggleButton tQueryTermButton : queryTermButtons) {
            tQueryTermButton.addActionListener(tQueryChangeListener);
        }

        panel = new JPanel();
        panel.setBackground(Color.BLACK);
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        panel.add(actualImageViewer);
        panel.add(tQueryTermButtonsPanel);
        panel.add(tSearchControlPanel);

        createImageResultButtons();
        artworkRetrievalManager = new ArtworkRetrievalManager(
                playlistEntry, imageResultButtons, resultInfoLabel, pArtworkRetriever);
    }

    private JPanel createSearchControlPanel() {
        JPanel tSearchControlPanel = new JPanel();
        tSearchControlPanel.setLayout(new BorderLayout());
        tSearchControlPanel.setBackground(Color.DARK_GRAY);

        queryField = new JTextField(20);
        tSearchControlPanel.add(queryField, BorderLayout.NORTH);

        phraseToggleButton = new JToggleButton("phrased");
        tSearchControlPanel.add(phraseToggleButton, BorderLayout.WEST);

        submitButton =  new JButton("find >>");
        submitButton.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                artworkRetrievalManager.performQuery(queryField.getText());
            }
        });
        tSearchControlPanel.add(submitButton, BorderLayout.EAST);

        resultInfoLabel = new JLabel();
        resultInfoLabel.setForeground(Color.WHITE);
        tSearchControlPanel.add(resultInfoLabel, BorderLayout.SOUTH);

        return tSearchControlPanel;
    }

    private void createImageResultButtons() {
        for (int i=0; i < 5; i++) {
            JButton tImageButton = new JButton();
            tImageButton.setEnabled(false);
            tImageButton.setPreferredSize(new Dimension(100,100));
            tImageButton.addActionListener(new ArtworkFileUpdater(playlistEntry, actualImageViewer, i));
            imageResultButtons.add(tImageButton);
            panel.add(tImageButton);
        }
    }

    private List<String> findQueryTerms() {
        String tArtistName = playlistEntry.getArtistName().replaceAll("\\(|\\)|\\,|\\-|\\[|\\]|\\/", " ");
        String tSongTitle = playlistEntry.getSongTitle().replaceAll("\\(|\\)|\\,|\\-|\\[|\\]|\\/", " ");
        tArtistName = tArtistName.replaceAll("\\s+", " ");
        tSongTitle = tSongTitle.replaceAll("\\s+", " ");
        String[] tArtistNameTokens = tArtistName.split(" ");
        String[] tSongTitleTokens = tSongTitle.split(" ");
        List<String> tTokens = new ArrayList<String>();
        tTokens.addAll(Arrays.asList(tArtistNameTokens));
        tTokens.addAll(Arrays.asList(tSongTitleTokens));
        return tTokens;
    }

    private JPanel createQueryTermButtonsPanel(List<String> tQueryTerms) {
        JPanel tQueryTermButtonsPanel = new JPanel();
        tQueryTermButtonsPanel.setBackground(Color.BLACK);
        GridLayout tGridLayout = new GridLayout(tQueryTerms.size(), 1);
        tQueryTermButtonsPanel.setLayout(tGridLayout);
        for (String tToken : tQueryTerms) {
            if (tToken.length() < 2) {
                continue;
            }
            final JToggleButton tQueryTermButton = new JToggleButton(tToken);
            tQueryTermButton.setPreferredSize(new Dimension(150,17));
            Font tFont = tQueryTermButton.getFont().deriveFont(10f);
            tQueryTermButton.setFont(tFont);
            tQueryTermButtonsPanel.add(tQueryTermButton);
            queryTermButtons.add(tQueryTermButton);
        }
        return tQueryTermButtonsPanel;
    }

    private ActionListener createQueryChangeListener() {
        return new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                QueryCreator tQueryCreator = QueryCreator.getInstance();
                String tQuery = tQueryCreator.createQuery(queryTermButtons, phraseToggleButton.isSelected());
                queryField.setText(tQuery);
            }
        };
    }

    private JLabel createActualImageViewer() {
        JLabel tImageViewerCanvas = new JLabel();
        tImageViewerCanvas.setMinimumSize(new Dimension(125,100));
        File tFile = AbstractP5TextureCacheManager.findArtworkFile(playlistEntry);
        Image tScaledInstance = defaultArtworkImage;
        if (tFile.exists()) {
            try {
                tScaledInstance = ImageIO.read(tFile).getScaledInstance(100, -1, Image.SCALE_SMOOTH);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        tImageViewerCanvas.setIcon(new ImageIcon(tScaledInstance));
        return tImageViewerCanvas;
    }

}
